/*
 *  Copyright (C) 2010 MADSA.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author:  Jorge Pintado de Santiago
 *          
 */

package com.madsa.maps;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.sisof.R;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MapsActivity extends MapActivity {
	
    private static final int SATELLITE_VIEW = Menu.FIRST;
    private static final int MAP_VIEW = Menu.FIRST+1;

    MyPositionOverlay positionOverlay;
	ArrayList<MapOverlays> destineOverlays;
	MapController mapController;
	private String[] destineLocations;
	private MapView myMapView;
		
	@Override
	protected boolean isRouteDisplayed() {
	  return false;
	}

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.maps);
		// Get a reference to the MapView
		myMapView = (MapView)findViewById(R.id.myMapView);
		// Get the Map View’s controller
		mapController = myMapView.getController();
		// Configure the map display options
		myMapView.setSatellite(false);
		myMapView.displayZoomControls(false);
		// Zoom in
		mapController.setZoom(17);
		//set enabled zoom controls
		myMapView.setBuiltInZoomControls(true);
		
		// Add the MyPositionOverlay
		positionOverlay = new MyPositionOverlay();
      
		Bundle extras  = getIntent().getExtras(); 
		if(extras != null){ 
			destineLocations = extras.getStringArray("destino");
		}else{
			destineLocations = getResources().getStringArray(R.array.locations);
		}
		destineOverlays = new ArrayList<MapOverlays>();
		for (String destine: destineLocations){
			String destineName = destine.split(";")[0].toString();
			String destineDirection = destine.split(";")[1].toString();

			Geocoder fwdGeocoder = new Geocoder(this);
			try{
				Address destineLocation = fwdGeocoder.getFromLocationName(destineDirection, 1).get(0);
				destineOverlays.add(new MapOverlays(destineName,
						destineLocation.getLatitude(),
						destineLocation.getLongitude()));
			}catch (IOException e) {}
		}

    
		List<Overlay> overlays = myMapView.getOverlays();
		overlays.add(positionOverlay);
		for(int i=0; i<destineOverlays.size(); i++){
			overlays.add(destineOverlays.get(i));
		}

		LocationManager locationManager;
		String context = Context.LOCATION_SERVICE;
		locationManager = (LocationManager)getSystemService(context);
		
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		String provider = locationManager.getBestProvider(criteria, true);
		
		Location location = locationManager.getLastKnownLocation(provider);
		updateWithNewLocation(location);
		
		locationManager.requestLocationUpdates(provider, 2000, 10,
				locationListener);
		
	}
  
	private void updateWithNewLocation(Location location) {
		TextView destineText;
		destineText = (TextView)findViewById(R.id.myLocationText);

		if (location != null) {		 
			
			// Update my location marker
			positionOverlay.setLocation(location);

			// Update the map location.
			Double geoLat = location.getLatitude()*1E6;
			Double geoLng = location.getLongitude()*1E6;
			GeoPoint point = new GeoPoint(geoLat.intValue(),
		                                geoLng.intValue());
			mapController.animateTo(point);
			
		} 
			destineText.setText("Destino: " + destineLocations[0].split(",")[0]);
	}

	private final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			updateWithNewLocation(location);
		}
		public void onProviderDisabled(String provider){
			updateWithNewLocation(null);
		}
		public void onProviderEnabled(String provider){ }
		public void onStatusChanged(String provider, int status,
								Bundle extras){ }
		};

		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			super.onCreateOptionsMenu(menu);
			menu.add(Menu.NONE, SATELLITE_VIEW, 0, R.string.m_satellite_view);
			menu.add(Menu.NONE, MAP_VIEW, 0, R.string.m_map_view);
			return true;
		}
    
		public boolean onMenuItemSelected(int featureId, MenuItem item) {
			super.onMenuItemSelected(featureId, item);
              	switch(item.getItemId()) {
              	case SATELLITE_VIEW:
              		myMapView.setSatellite(true);
              		break;
              	case MAP_VIEW:
              		myMapView.setSatellite(false);
              		break;
              	}
              	return true;
		}
}